//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "BoxSearchViewController.h"
#import "RestaurantDetailViewController.h"
#import "Config.h"
#import "SearchCell.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "LoadMoreCell.h"
#import "MapResultViewController.h"
#import "OMGToast.h"
#import "RequestLoadingView.h"
@interface BoxSearchViewController ()

@end

@implementation BoxSearchViewController
@synthesize lbTips;
@synthesize lbAddress;
@synthesize mainTable;
@synthesize reqSearch;
@synthesize reqSearchMore;
@synthesize arrayArea;
@synthesize arrayDistrict;
@synthesize arrayConsume;
@synthesize arrayCuisine;
@synthesize arrayCuisineType;
@synthesize reqArea;
@synthesize reqCuisine;
@synthesize reqConsume;
@synthesize _selectedIndex,_selectedTypeIndex,areaName;
//@synthesize cityId;
//@synthesize areaId;
//@synthesize diningDate;
//@synthesize diningTime;
//@synthesize boxType;
//@synthesize capacity;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    wqTable = mainTable;
    lbAddress.text = [[Config Instance]getLocation];
    arrayOrderBy = [NSMutableArray arrayWithObjects:
      [NSDictionary dictionaryWithObjectsAndKeys:@"折扣由大到小",@"text", @"discount",@"id",nil],
      [NSDictionary dictionaryWithObjectsAndKeys:@"评分由高到低",@"text", @"score",@"id",nil],
      [NSDictionary dictionaryWithObjectsAndKeys:@"距离由近到远",@"text", @"distance",@"id",nil],
      nil];
    orderBy = @"discount";
    pageIndex=1;
    
    [self startRequest];
    
    _lbArea.text = areaName;
    
    

    }

- (void)startRequest
{
    if(!loadingView)
    {
            loadingView = [[RequestLoadingView alloc]
                               initRequestLoadingView:self
                               queueFinishSelector:nil
                               viewFrame:LoadingViewFrame];
    }
    
    [self getSearchResult];
    [self getArea];
    [self getCuisine];
    [self getCounsume];
    
    [loadingView addRequestToQueue:reqSearch];
    [loadingView addRequestToQueue:reqArea];
    [loadingView addRequestToQueue:reqCuisine];
    [loadingView addRequestToQueue:reqConsume];
    
    [loadingView startRequestQueue];
    
}

- (void) getSearchResult{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_searchBox];
    isSearchFinished = false;
    reqSearch=[ASIFormDataRequest requestWithURL:url];
    [reqSearch setPostValue:[NSString stringWithFormat:@"%d",pageIndex++] forKey:@"pageIndex"];
    [reqSearch setPostValue:[NSString stringWithFormat:@"%d",[[Config Instance] getCityId]] forKey:@"cityID"];
    if(_areaId != 0)
        [reqSearch setPostValue:[NSString stringWithFormat:@"%d",_areaId] forKey:@"areaID"];
    if(_boxType != 0)
        [reqSearch setPostValue:[NSString stringWithFormat:@"%d",_boxType] forKey:@"boxTypeID"];
    if(_capacity != 0)
        [reqSearch setPostValue:[NSString stringWithFormat:@"%d",_capacity] forKey:@"boxCapacityID"];
    if(_cuisineId != 0)
        [reqSearch setPostValue:[NSString stringWithFormat:@"%d",_cuisineId] forKey:@"cuisineID"];
    if(_avgConsumeID != 0)
        [reqSearch setPostValue:[NSString stringWithFormat:@"%d",_avgConsumeID] forKey:@"avgConsumeID"];
    [reqSearch setPostValue:_diningDate forKey:@"diningDate"];
    [reqSearch setPostValue:[NSString stringWithFormat:@"%d",_diningTime] forKey:@"diningTime"];
    [reqSearch setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLatitude]] forKey:@"latitude"];
    [reqSearch setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLongitude]] forKey:@"longitude"];
    [reqSearch setPostValue:orderBy forKey:@"orderBy"];
    [reqSearch setShouldAttemptPersistentConnection:NO];
    [reqSearch setDidFinishSelector:@selector(finishSearch:)];
    [reqSearch setDelegate: self];
    
    if (!loadingView.bFirstRequest) {
        [reqSearch startAsynchronous];
    }
    
    [tableDataArray removeAllObjects];
    [mainTable reloadData];
}
//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)finishSearch:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *jsonStr = [request responseString];
//    NSLog(@"%@",jsonStr);
    NSDictionary *dic = [jsonStr JSONValue];
    
    tableDataArray = [dic valueForKey:@"data"];
    //NSLog(@"%@", tableDataArray);
    returnCount = [tableDataArray count];
    
    delegate=self;
    
    [mainTable reloadData];
    [Config setExtraCellLineHidden:mainTable];
    isSearchFinished = true;

    if(returnCount == 0){
//        lbTips.hidden = false;
//        lbTips.text = @"没有符合条件的记录。";
        [OMGToast showWithText:@"没有符合条件的记录。" bottomOffset:50 duration:3];
    }
}
- (void) getCuisine
{
    NSURL *url = [NSURL URLWithString:url_cuisineListWithType] ;
    reqCuisine = [ASIHTTPRequest requestWithURL:url];
    [reqCuisine setDidFinishSelector:@selector(finishCuisine:)];
    [reqCuisine setShouldAttemptPersistentConnection:NO];
    reqCuisine.delegate = self;
    isCuisineFinished = false;
    
    if (!loadingView.bFirstRequest)
    {
        [reqCuisine startAsynchronous];
    }
    
}
- (void)finishCuisine:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    //    arrayCuisine = [dic valueForKey:@"data"];
    //    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    //                          @"0",@"cuisineID",@"不限",@"cuisineName",nil];
    //    [arrayCuisine insertObject: dict atIndex:0];
    NSMutableArray *data = [dic valueForKey:@"data"];
    arrayCuisineType = [[NSMutableArray alloc]init];
    for (int i=0;i<data.count;i++) {
//        NSDictionary *dic = data[i];
//        NSString *cuisine = [dic valueForKey:@"cuisinesType"];
//        NSString *cuisineCode=[cuisine componentsSeparatedByString:@"-"][0];
//        NSString *cuisineName=[cuisine componentsSeparatedByString:@"-"][1];
        NSDictionary *dic = [data objectAtIndex:i];
        NSString *cuisine = [dic valueForKey:@"cuisinesType"];
        NSString *cuisineCode=[[cuisine componentsSeparatedByString:@"-"] objectAtIndex:0];
        NSString *cuisineName=[[cuisine componentsSeparatedByString:@"-"] objectAtIndex:1];
        
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              cuisineCode,@"cuisineCode",cuisineName,@"cuisineName",[dic valueForKey:@"cuisinesList"],@"cuisinesList",nil];
        [arrayCuisineType insertObject:dict atIndex:i];
    }
    //默认全部
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"cuisineID",@"全部菜系",@"cuisineName",nil];
    arrayCuisine = [[NSMutableArray alloc]init];
    [arrayCuisine insertObject: dict atIndex:0];
    NSDictionary *all = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"0",@"cuisineCode",@"全部菜系",@"cuisineName",arrayCuisine,@"cuisinesList",nil];
    [arrayCuisineType insertObject: all atIndex:0];
    isCuisineFinished = true;
}
- (void) getArea{
    //异步请求
    //    NSDictionary *dic =[arrayCity objectAtIndex:0];
    //    cityId = [[dic valueForKey:@"cityID"] intValue];
    cityId = [[Config Instance]getCityId];

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?cityID=%d",url_areaWithDistrict,cityId]] ;
    reqArea = [ASIHTTPRequest requestWithURL:url];
    [reqArea setDidFinishSelector:@selector(finishArea:)];
    isAreaFinished = false;
    [reqArea setShouldAttemptPersistentConnection:NO];
    [reqArea setDelegate: self];
    if (!loadingView.bFirstRequest) {
        [reqArea startAsynchronous];
    }
    
}
- (void)finishArea:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    arrayDistrict = [[NSMutableArray alloc]init];
    for (int i=0;i<data.count;i++) {
//        NSDictionary *dic = data[i];
//        NSString *county = [dic valueForKey:@"county"];
//        NSString *countyCode=[county componentsSeparatedByString:@"-"][0];
//        NSString *countyName=[county componentsSeparatedByString:@"-"][1];
        NSDictionary *dic = [data objectAtIndex:i];
        NSString *county = [dic valueForKey:@"county"];
        NSString *countyCode=[[county componentsSeparatedByString:@"-"] objectAtIndex:0];
        NSString *countyName=[[county componentsSeparatedByString:@"-"] objectAtIndex:1];
        
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              countyCode,@"countyCode",countyName,@"countyName",[dic valueForKey:@"areaList"],@"areaList",nil];
        [arrayDistrict insertObject:dict atIndex:i];
    }
    //默认全部
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"areaID",@"全部商圈",@"areaName",nil];
    arrayArea = [[NSMutableArray alloc]init];
    [arrayArea insertObject: dict atIndex:0];
    NSDictionary *all = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"0",@"countyCode",@"全部商圈",@"countyName",arrayArea,@"areaList",nil];
    [arrayDistrict insertObject: all atIndex:0];
    isAreaFinished = true;
    areaId = 0;
}
- (void) getCounsume{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_avgConsumeList];
    reqConsume = [ASIHTTPRequest requestWithURL:url];
    [reqConsume setDidFinishSelector:@selector(finishConsume:)];
    isConsumeFinished = false;
    [reqConsume setShouldAttemptPersistentConnection:NO];
    [reqConsume setDelegate: self];
    
    if (!loadingView.bFirstRequest) {
        [reqConsume startAsynchronous];
    }
    
}
- (void)finishConsume:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayConsume = [dic valueForKey:@"data"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"avgConsumeID",@"不限",@"avgConsume",nil];
    [arrayConsume insertObject: dict atIndex:0];
    isConsumeFinished = true;
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
    isSearchFinished = true;
    isSearchMoreFinished = true;
    isAreaFinished = true;
    isCuisineFinished=true;
    isConsumeFinished=true;
}

- (void)viewDidUnload
{
    [self setMainTable:nil];
    wqTable = nil;
    [self setLbAddress:nil];
    [self setLbTips:nil];
    [self setLbArea:nil];
    [self setLbCuisine:nil];
    [self setLbConsume:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        self.title=@"搜索结果";
//    }
//    return self;
//}
// customize the number of rows in the table view
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] < ([tableDataArray count])) {
        return 90;
    }else{
        return 40;
    }
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"SearchCellIdentifier";
    
        
    if([indexPath row] < ([tableDataArray count])) {
        
        SearchCell *cell = (SearchCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
       if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"SearchCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
       }
        
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        
        
        cell.name = [item valueForKey:@"name"];
        cell.address = [item valueForKey:@"address"] ;
        cell.distance = [item valueForKey:@"distance"] ==[NSNull null]?@"未知" : [NSString stringWithFormat:@"%f",[[item valueForKey:@"distance"] floatValue] ];
        cell.cuisine = [item valueForKey:@"cuisine"] ==[NSNull null]?@"未知" : [item valueForKey:@"cuisine"];
        cell.discount = [item valueForKey:@"discount"] ==[NSNull null]?@"10":[[item valueForKey:@"discount"]stringValue];
        cell.score = [item valueForKey:@"score"] == [NSNull null]? [NSNumber numberWithFloat:0] : [NSNumber numberWithFloat:[[item valueForKey:@"score"] floatValue]];
        cell.boxes = [[item valueForKey:@"boxs"] intValue];
        cell.agree = [[item valueForKey:@"isAgreement"] intValue];

//        显示图片
        NSString * imageStr = [[tableDataArray objectAtIndex:indexPath.row] valueForKey:@"image"];
        NSString *imageName =@"";
        if (![imageStr isEqual:[NSNull null] ]) {
            NSArray *array = [imageStr componentsSeparatedByString:@"/"];
            imageName = [array lastObject];
        }
        NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
        if (image) {
            cell.imageView.image = image;
        }
        else
        {
            cell.imageView.image = [UIImage imageNamed:@"placeholder.png"];
            //placeholder为在未加载完成加载图片时显示的默认图片
        }
        return cell;

    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
          
          if(returnCount<pageSize){
              cell.lbText.text=@"";
              cell.hidden = true;
          }else{
              //创建loadMoreCell
              cell.lbText.text=str_more;
            
          }
          cell.textLabel.textAlignment = UITextAlignmentCenter;
          cell.detailTextLabel.text=@"";
          cell.imageView.image =nil;
          return cell;

    }
    
}
-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UITableViewCell *cell = [wqTable cellForRowAtIndexPath:indexPath];
        if(image)
        {
            cell.imageView.image = image;
        }
    });


}

- (IBAction)showSort:(id)sender {
    if(!isShowed){
        selectIndex = 1;
        LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择排序方式" options:arrayOrderBy fullHeight:200];
        lplv.name = @"text";
        lplv.delegate = self;
        lplv.selectedIndex = _selectedIndex2;
        [lplv showInView:self.view animated:YES];
        isShowed = true;
    }
}

- (IBAction)doBack:(id)sender {
    if(!isSearchFinished){
        [reqSearch clearDelegatesAndCancel];
        [reqSearch cancel];
    }if(!isSearchMoreFinished){
        [reqSearchMore clearDelegatesAndCancel];
        [reqSearchMore cancel];
    }if(!isAreaFinished){
        [reqArea clearDelegatesAndCancel];
        [reqArea cancel];
    }if(!isConsumeFinished){
        [reqConsume clearDelegatesAndCancel];
        [reqConsume cancel];
    }if(!isCuisineFinished){
        [reqCuisine clearDelegatesAndCancel];
        [reqCuisine cancel];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)showMap:(id)sender {
    MapResultViewController  *view = [[MapResultViewController alloc] initWithNibName:@"MapResultViewController" bundle:nil];
    //    view.results = tableDataArray;
    //    [self.view addSubview:view.view];
    [view.view setFrame:self.view.bounds];
    [view resetAnnitations:tableDataArray];
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
}

- (IBAction)showArea:(id)sender {
    selectIndex = 2;
    //if(_selectedTypeIndex!=0){
//    arrayArea = [arrayDistrict[_selectedTypeIndex] objectForKey:@"areaList"];
    //}
    arrayArea = [[arrayDistrict objectAtIndex: _selectedTypeIndex] objectForKey:@"areaList"];

    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择商圈" options:arrayArea types:arrayDistrict fullHeight:20];
    lplv.name = @"areaName";
    lplv.typeName = @"countyName";
    lplv.listName = @"areaList";
    lplv.selectedTypeIndex = _selectedTypeIndex;
    lplv.selectedIndex = _selectedIndex;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
}

- (IBAction)showCuisine:(id)sender {
    selectIndex = 3;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择菜系" options:arrayCuisine types:arrayCuisineType fullHeight:20];
    lplv.name = @"cuisineName";
    lplv.typeName = @"cuisineName";
    lplv.listName = @"cuisinesList";
    lplv.selectedTypeIndex = _selectedTypeIndex1;
    lplv.selectedIndex = _selectedIndex1;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
}

- (IBAction)showConsume:(id)sender {
    selectIndex = 5;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择人均消费" options:arrayConsume fullHeight:20];
    lplv.name = @"avgConsume";
    lplv.selectedIndex = _selectedIndex3;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == [tableDataArray count]) {
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
        
//        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
//        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSURL *url = [NSURL URLWithString:url_searchBox];
        reqSearchMore =[ASIFormDataRequest requestWithURL:url];
        [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",pageIndex++] forKey:@"pageIndex"];
        [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",_cityId] forKey:@"cityID"];
        if(_areaId != 0)
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",_areaId] forKey:@"areaID"];
        if(_boxType != 0)
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",_boxType] forKey:@"boxTypeID"];
        if(_capacity != 0)
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",_capacity] forKey:@"boxCapacityID"];
        if(_avgConsumeID != 0)
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",_avgConsumeID] forKey:@"avgConsumeID"];
        if(_cuisineId !=0)
            [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",_cuisineId] forKey:@"cuisineID"];
        [reqSearchMore setPostValue:_diningDate forKey:@"diningDate"];
        [reqSearchMore setPostValue:[NSString stringWithFormat:@"%d",_diningTime] forKey:@"diningTime"];
        [reqSearchMore setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLatitude]] forKey:@"latitude"];
        [reqSearchMore setPostValue:[NSString stringWithFormat:@"%f",[[Config Instance] getLongitude]] forKey:@"longitude"];
        [reqSearchMore setPostValue:orderBy forKey:@"orderBy"];
        [reqSearchMore setShouldAttemptPersistentConnection:NO];
        reqSearchMore.delegate = self;
        [reqSearchMore setDidFinishSelector:@selector(appendTableWith:)];
        [reqSearchMore startAsynchronous];
        isSearchMoreFinished = false;
//        NSString *jsonStr = [request responseString];
//        
//        NSDictionary *dic = [jsonStr JSONValue];
//        NSMutableArray *array = [dic valueForKey:@"data"];
//        returnCount = [array count];
//        [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
//        [dic release];
//        [array release];
        return;
    }else{
        RestaurantDetailViewController  *view = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
        //传递商户id参数
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        SearchCell *cell=(SearchCell *)[tableView cellForRowAtIndexPath:indexPath];
        view.distance = [cell.distanceLable.text copy];
        view.merchantId =[[item objectForKey:@"ID"] intValue];
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
//        [view release];

    }
    //其他cell的事件
    
}
-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    isSearchMoreFinished = true;

    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    returnCount = [data count];
    //    [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [self.mainTable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [self.mainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
}

//-(void) appendTableWith:(NSMutableArray *)data
//{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
//    for (int i=0;i<[data count];i++) {
//        [tableDataArray addObject:[data objectAtIndex:i]];
//    }
//    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
//    for (int ind = 0; ind < [data count]; ind++) {
//        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
//        [insertIndexPaths addObject:newPath];
//    }
//    //重新调用UITableView的方法, 来生成行.
//    [self.mainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
//}

#pragma mark - LeveyPopListView delegates
- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex options:(NSArray *)_options didSelectedTypeIndex:(NSInteger)anTypeIndex
{
    switch (selectIndex) {
        case 1:{
            orderBy = [[arrayOrderBy objectAtIndex:anIndex] objectForKey:@"id"];
            _selectedIndex2 = anIndex;
            break;
        }
        case 2:{
            _selectedIndex = anIndex;
            _selectedTypeIndex = anTypeIndex;
            
            _lbArea.text = [NSString stringWithFormat:@"%@",[[_options objectAtIndex:anIndex] objectForKey:@"areaName"]];
            
            _areaId = [[[_options objectAtIndex:anIndex] objectForKey:@"areaID"] intValue];
            break;
        }
        case 3:{
            _selectedIndex1 = anIndex;
            _selectedTypeIndex1 = anTypeIndex;
            arrayCuisine = [_options copy];
            _lbCuisine.text = [NSString stringWithFormat:@"%@",[[_options objectAtIndex:anIndex] objectForKey:@"cuisineName"]];
            
            _cuisineId = [[[_options objectAtIndex:anIndex] objectForKey:@"cuisineID"] intValue];
            break;
        }
        case 5:{
            _selectedIndex3 = anIndex;
            if (_selectedIndex3==0)
                _lbConsume.text = AVG_CONSUME;
            else
                _lbConsume.text = [NSString stringWithFormat:@"%@",[[arrayConsume objectAtIndex:anIndex] objectForKey:@"avgConsume"]];
            
            _avgConsumeID = [[[arrayConsume objectAtIndex:anIndex] objectForKey:@"avgConsumeID"] intValue];
            break;
        }
            
    }
    pageIndex = 1;
    isShowed = false;
    
    [self getSearchResult];
}

- (void)leveyPopListViewDidCancel
{
    isShowed = false;
}



@end
